package com.hxbd.test.utils;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.SocketException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.log4j.Logger;
import org.bson.conversions.Bson;
import org.testng.Assert;
import org.testng.Reporter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.duan.test.utils.common.HttpClientUtils;
import com.duan.test.utils.common.JdbcUtils;
import com.duan.test.utils.common.core.HttpEntityType;
import com.duan.test.utils.common.core.HttpRequestConfig;
import com.duan.test.utils.common.core.HttpRequestResult;
import com.hxbd.test.Beans.TResult;
import com.hxbd.test.handles.DataRetrieveHandlers;
import com.hxbd.test.handles.GetAllClassHandler;
import com.hxbd.test.handles.ParamNotExistException;
import com.mongodb.client.model.Filters;
import com.opera.core.systems.internal.StackHashMap;

public class InterfaceUtils extends PlatformUtil {
	private static Logger log = Logger.getLogger(InterfaceUtils.class);
	private  Map<String, Object> localparamsmap = null;
	private static final String[] fields = new String[] {"code","_data_","message"};
	private static Set<String> set = new HashSet<String>(Arrays.asList(fields));
	protected static Map<String,Object> parammap = new LinkedHashMap<String, Object>();
	public static Map<String, Object> getParammap() {
		return parammap;
	}

	public InterfaceUtils() {

	}

	private static Map<String, Object> actualrm = new HashMap<String, Object>();

	public static Map<String, Object> getActualrm() {
		return actualrm;
	}

	protected static String Tlevel;

	public static String getTlevel() {
		return Tlevel;
	}

	public static void setTlevel(String tlevel) {
		Tlevel = tlevel;
	}

	protected static MongoUtil mongoutil = null;
	protected String msyqlAdd;

	/**
	 *初始化数据库数据
	 * 
	 * @return 事务执行成功数
	 */
	protected AtomicInteger initSqlData() {
		final AtomicInteger succount = new AtomicInteger(0);
		Map<String, List<Map<String, Object>>>  map = ReadDBConfigFromXml.readDbConfig();
		for (Map<String, Object> m : map.get(getTestEnv())) {
			Boolean isSync = (Boolean) m.get("synchronized");
			List<Map<String,String>> ll = (List<Map<String,String>>)m.get("data");
			if (isSync) {
				Vector<Thread> threads = new Vector<Thread>();  
				for (Map<String,String> m2 : ll) {
					Thread t = new Thread(new Runnable() {
						@Override
						public void run() {
							JdbcUtils jdbc = new JdbcUtils(m2.get("driver"), m2.get("url"), m2.get("user"), m2.get("pwd"));
							try {
								succount.getAndAdd(jdbc.commitwithtrans(m2.get("init").split(";")));
							} catch (Exception e1) {
								// TODO Auto-generated catch block
								Assert.fail(e1.getCause().toString());
							} finally {
								jdbc.closeDBResource();
							}
						}
					});
					threads.add(t);
					t.start();
				}
				for (Thread iThread : threads) {  
				      try {  
				        // 等待所有线程执行完毕  
				        iThread.join();  
				      } catch (InterruptedException e) {  
				        e.printStackTrace();  
				      }  
				}	
			}
			else {
				for (Map<String,String> m2 : ll) {
					JdbcUtils jdbc = new JdbcUtils(m2.get("driver"), m2.get("url"), m2.get("user"), m2.get("pwd"));
					try {
						succount.getAndAdd(jdbc.commitwithtrans(m2.get("init").split(";")));
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						Assert.fail(e1.getCause().toString());
					} finally {
						jdbc.closeDBResource();
					}
				}
			}
		}
		return succount;
	}
	/**
	 *清理数据库数据，初始化环境
	 * 
	 * @return 事务执行成功数
	 */
	protected AtomicInteger deleteSqlData() {
		final AtomicInteger succount = new AtomicInteger(0);
		Map<String, List<Map<String, Object>>>  map = ReadDBConfigFromXml.readDbConfig();
		for (Map<String, Object> m : map.get(getTestEnv())) {
			Boolean isSync = (Boolean) m.get("synchronized");
			List<Map<String,String>> ll = (List<Map<String,String>>)m.get("data");
			if (isSync) {
				Vector<Thread> threads = new Vector<Thread>();  
				for (Map<String,String> m2 : ll) {
					Thread t = new Thread(new Runnable() {
						@Override
						public void run() {
							JdbcUtils jdbc = new JdbcUtils(m2.get("driver"), m2.get("url"), m2.get("user"), m2.get("pwd"));
							try {
								succount.getAndAdd(jdbc.commitwithtrans(m2.get("complete").split(";")));
							} catch (Exception e1) {
								// TODO Auto-generated catch block
								Assert.fail(e1.getCause().toString());
							} finally {
								jdbc.closeDBResource();
							}
						}
					});
					threads.add(t);
					t.start();
				}
				for (Thread iThread : threads) {  
				      try {  
				        // 等待所有线程执行完毕  
				        iThread.join();  
				      } catch (InterruptedException e) {  
				        e.printStackTrace();  
				      }  
				}	
			}
			else {
				for (Map<String,String> m2 : ll) {
					JdbcUtils jdbc = new JdbcUtils(m2.get("driver"), m2.get("url"), m2.get("user"), m2.get("pwd"));
					try {
						succount.getAndAdd(jdbc.commitwithtrans(m2.get("complete").split(";")));
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						Assert.fail(e1.getCause().toString());
					} finally {
						jdbc.closeDBResource();
					}
				}
			}
		}
		return succount;
	}

	protected void deleteMongo(String testEnv) {
		Bson filter = null;
		if (testEnv.trim().equals("test")) {
			filter = Filters.in("orgCode", new String[] { "2000AZ01", "2000AZ02", "2000AZ" });
		} else if (testEnv.trim().equals("product")) {
			filter = Filters.in("orgCode", new String[] { "200ILV010101", "200ILV010102", "200ILV0101" });
		}
		mongoutil.deleteMany("driver_statistics", filter);
		mongoutil.deleteMany("truck_statistics", filter);
		mongoutil.deleteMany("org_statistics", filter);
	}

	/**
	 * 初始化并插入测试数据
	 * 
	 * @param testEnv
	 */
	protected void initTestData(String testEnv) {
		// if (testEnv.equals("test")) {
		// try {
		// if (testEnv.trim().equalsIgnoreCase("test")) {
		// mongoutil = new MongoUtil("172.16.1.41", 27017, "rwuser",
		// "rwuser", "test");
		// } else if (testEnv.trim().equalsIgnoreCase("demo")) {
		// mongoutil = new MongoUtil("172.18.4.134", 27017, "rwuser",
		// "rwuser", "demo");
		// } else if (testEnv.trim().equalsIgnoreCase("product")) {
		// mongoutil = new MongoUtil(
		// "dds-bp156bdc749ae6d42.mongodb.rds.aliyuncs.com",
		// 3717, "root", "iomFn2Yo8", "stats");
		// }
		// deleteMongo(testEnv);
		// // 插入mongodb数据
		// mongoutil.insertMongoDataFromExcel(
		// CommonUtils.getFilePath("\\TestData\\" + testEnv
		// + "\\testData.xlsx"), "driver_statistics");
		// mongoutil.insertMongoDataFromExcel(
		// CommonUtils.getFilePath("\\TestData\\" + testEnv
		// + "\\testData.xlsx"), "truck_statistics");
		// mongoutil.insertMongoDataFromExcel(
		// CommonUtils.getFilePath("\\TestData\\" + testEnv
		// + "\\testData.xlsx"), "org_statistics");
		// } catch (Exception e) {
		// Assert.fail(e.getCause().toString());
		// mongoutil.close();
		// }
		// // 初始化并插入mysql数据
		// Assert.assertTrue(deleteTestSqlData() >= 0);
		// }
		initSqlData();
		// if (testEnv.trim().equalsIgnoreCase("test")) {
		// Assert.assertTrue(insertTestSqlData() == 14);
		// } else if (testEnv.trim().equalsIgnoreCase("product")) {
		//// Assert.assertTrue(insertTestSqlData() == 1);
		// }

		// // rocketmq中发送消息
		// RockectMqProduce rmq = new RockectMqProduce(
		// "group_con_liquidometer_realtime", "172.16.1.44:9876",
		// "manualTestProduceTesting1");
		// rmq.start();
		// try {
		// // 发送excel数据作为消息(excel格式参考fueltest.xlsx)
		// rmq.sendMsgForExcel(CommonUtils.getFilePath("\\TestData\\fueltest.xlsx"),
		// "fuel", "topic_gps_liquidometer", "*",
		// "107015090001893",InterfaceUtils.now(),"yyyy-MM-dd HH:mm:ss",10,3000,1);
		// //根据文件内容发送
		// rmq.sendMsgFromFile("C:\\Users\\Huoyunren\\Desktop\\test.txt","topic_ctbox12",
		// "*",
		// "107015090001893",InterfaceUtils.now(),"yyyy-MM-dd HH:mm:ss",10,0,0,1);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// StringWriter sw = new StringWriter();
		// e.printStackTrace(new PrintWriter(sw, true));
		// Assert.fail(sw.toString());
		// }
		// // 发送单个消息
		// rmq.sendMsg("topic_gps_liquidometer", "*", "107015090001893",
		// JSONObject.parseObject("{}"));
		// rmq.close();
	}
	/**
	 * 清除测试数据，初始化环境
	 * 
	 * @param testEnv
	 */
	protected void delTestData(String testEnv) {
		deleteSqlData();
//		if (testEnv.equals("test")) {
//		deleteMongo(testEnv);
//		mongoutil.close();
//		Assert.assertTrue(deleteTestSqlData() >= 0);
//	}
	}
	public static void put(Map m, Object key, Object value) {
		if (m.containsKey(key)) {
			Assert.fail("不能向map中添加重复key");
		} else {
			m.put(key, value);
		}
	}

	private static List<RockectMqProduce> rmqmap = new ArrayList<RockectMqProduce>();

	public static List<RockectMqProduce> getRmqmap() {
		return rmqmap;
	}

	/**
	 * 结束所有MQ生产者,并终止程序
	 */
	protected static void closeAllMQProducer() {
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				// 使用关闭钩子来关闭资源
				for (RockectMqProduce rmq : rmqmap) {
					if (rmq != null) {
						try {
							rmq.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}

				System.out.println("程序关闭了物理资源");
			}
		});
		System.exit(0);
	}

	public boolean equalList(List<?> list1, List<?> list2) {
		if (list1.size() != list2.size()) {
			return false;
		}
		if (list2.containsAll(list1)) {
			return true;
		} else {
			return false;
		}
	}


	public static String paramsconvert(Map<String, String> params){
		String paramsStr = "";
		int paramcount = 0;
		Map<String, Object> m = InterfaceUtils.getActualrm();
		for (String key : params.keySet()) {
			String value = params.get(key);
			for (String key2 : m.keySet()) {
				if (value.contains(key2)) {
					Object mapvalue = m.get(key2);
					if (mapvalue == null) {
						mapvalue = "";
					}
					value = value.replaceAll(replaceSpecialChar(key2), mapvalue.toString());
				}
			}
			try {
				value = invokeAllMethod(value);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Assert.fail("反射调用方法失败", e.fillInStackTrace());
			}
			if (paramcount == 0) {
				paramsStr += "?" + key + "=" + value;
//				paramsStr += "?" + key + "=" + getURLEncoder(value);
			} else {
				paramsStr += "&" + key + "=" + value;
//				paramsStr += "&" + key + "=" + getURLEncoder(value);
			}
			paramcount++;
		}
		return paramsStr;
	}

	/**
	 * 
	 * @param apiurl
	 * @param sendmethod
	 * @param params
	 * @param headers
	 * @param body
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static JSONObject callInterface(String apiurl, String sendmethod, String params, Map<String, String> headers,
			String body) {
		String paramsStr = params;
		JSONObject response = null;
		try {
			if (params!= null && !params.isEmpty() && ObjectCompare.isJsonObject(params)) {
				paramsStr = paramsconvert(JSON.parseObject(params, new TypeReference<Map<String, String>>() {
				}));
			}
			apiurl = apiurl + "?" + paramsStr;
			HttpRequestConfig config = HttpRequestConfig.create().url(apiurl);
			if (apiurl.contains("https")) {
				config.useSSL();
			}
			if (sendmethod.equalsIgnoreCase("post")) {
				if (!headers.isEmpty()) {
					for (String key : headers.keySet()) {
						config.addHeader(key, headers.get(key));
					}
				}
				if (!headers.containsKey("Content-Type")) {
					headers.put("Content-Type", "application/x-www-form-urlencoded");
					config.addHeader("Content-Type", "application/x-www-form-urlencoded");
				}
				if (!body.isEmpty()) {
					if (ObjectCompare.isJson(body)) {
						JSON json = (JSON) JSON.parse(body);
						if (headers.get("Content-Type").toString().contains("json")) {
							config.json(invokeAllMethod(json.toString()));
							config.httpEntityType(HttpEntityType.ENTITY_STRING);
						}
						else if (headers.get("Content-Type").toString().contains("x-www-form-urlencoded")) {
							Map<String,Object> tmpmap = new HashMap<String,Object>();
							if (!body.isEmpty()) {
								for (Map.Entry<String, Object> entry : ((Map<String,Object>)json).entrySet()) {
									tmpmap.put(entry.getKey(), invokeAllMethod(entry.getValue().toString()));
								}
							}
							config.paramMap(tmpmap);
							config.httpEntityType(HttpEntityType.ENTITY_FORM);
						}
						else if (headers.get("Content-Type").toString().contains("form-data")) {
							Map<String,Object> tmpmap = new HashMap<String,Object>();
							if (!body.isEmpty()) {
								for (Map.Entry<String, Object> entry : ((Map<String,Object>)json).entrySet()) {
									tmpmap.put(entry.getKey(), invokeAllMethod(entry.getValue().toString()));
								}
							}
							config.paramMap(tmpmap);
							config.httpEntityType(HttpEntityType.ENTITY_MULTIPART);
						}
					}
					else {
						config.json(invokeAllMethod(body));
						config.httpEntityType(HttpEntityType.ENTITY_STRING);
					}
				}
				else {
					if (headers.get("Content-Type").toString().contains("x-www-form-urlencoded")) {
						config.httpEntityType(HttpEntityType.ENTITY_FORM);
					}
					else if (headers.get("Content-Type").toString().contains("form-data")) {
						config.httpEntityType(HttpEntityType.ENTITY_MULTIPART);
					}
					else {
						config.httpEntityType(HttpEntityType.ENTITY_STRING); 
					}
				}
				HttpRequestResult result = HttpClientUtils.post(config);
				response  = JSON.parseObject(result.getResponseText());
			} else if (sendmethod.equalsIgnoreCase("get")) {
				if (null != headers && !headers.isEmpty()) {
					for (String key : headers.keySet()) {
						config.addHeader(key, headers.get(key));
					}
				}
		        HttpRequestResult result = HttpClientUtils.get(config);
		        response  = JSON.parseObject(result.getResponseText());
			}
		}
		catch (UnsupportedEncodingException e) {
			// TODO: handle exception
			Assert.fail("接口调用失败",e.fillInStackTrace());
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			Assert.fail("接口调用失败",e.fillInStackTrace());
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			Assert.fail("接口调用失败",e.fillInStackTrace());
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			Assert.fail("接口调用失败",e.fillInStackTrace());
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			Assert.fail("接口调用失败",e.fillInStackTrace());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Assert.fail("接口调用失败",e.fillInStackTrace());
		}
		return response;
//		try {
//			// 获取返回数据
//			HttpEntity entity = response.getEntity();
//			String resString = null;
//			try {
//				resString = EntityUtils.toString(entity, "utf-8");
//			} catch (org.apache.http.ParseException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			JSONObject jsonobj = JSON.parseObject(resString);
//			return jsonobj;
//		} finally {
//			try {
//				response.close();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
	}

	/**
	 * 获得添加成功的结果对象
	 * 
	 * @param json
	 * @return Object
	 */
	public static Object getResult(JSONObject json) {
		// TODO Auto-generated method stub
		Object jsonResult = null;
		if (json.getIntValue("code") == 0) {
			jsonResult = json.getJSONObject("data").get("result") == null ? json.getJSONObject("data")
					: json.getJSONObject("data").get("result");
		}
		return jsonResult;
	}

	/**
	 * 获得添加成功的结果对象
	 * 
	 * @param json
	 * @return Object
	 */
	public static Object getResult2(JSONObject json, String Paras) {
		// TODO Auto-generated method stub
		Object jsonResult = null;
		JSONObject myJsonObject;
		if (json.getIntValue("code") == 0 && json.getJSONObject("data").getString("success").equals("true")) {
			myJsonObject = JSON.parseObject(Paras);
			myJsonObject.remove("autoBind");
			jsonResult = myJsonObject;
		}
		return jsonResult;
	}

	/**
	 * 中文标点转英文
	 * 
	 * @param str_CHN
	 * @return
	 */
	public static String strCHNToEN(String str_CHN) {
		String[] regs = { "！", "，", "。", "；", "【", "】", "“", "”", "!", ",", ".", ";", "[", "]", "\"", "\"" };
		for (int i = 0; i < regs.length / 2; i++) {
			str_CHN = str_CHN.replaceAll(regs[i], regs[i + regs.length / 2]);
		}
		return str_CHN;
	}
	/**
	 * 中文标点转英文
	 * 
	 * @param str_CHN
	 * @return
	 */
	public static String strCHNToEN(String str_CHN,String []regs) {
		for (int i = 0; i < regs.length / 2; i++) {
			str_CHN = str_CHN.replaceAll(regs[i], regs[i + regs.length / 2]);
		}
		return str_CHN;
	}
	/**
	 * 接口测试检查
	 * 
	 * @param returnrule
	 *            接口返回规则
	 * @param json
	 *            接口返回json
	 * @param Paras
	 *            入参
	 * @param code
	 *            期望code
	 * @param msg
	 *            期望msg
	 * @param result
	 *            期望结果验证
	 * @param resultnum
	 *            期望结果条数
	 */
	public static void InterfaceCheck(Map<String, String> returnrule, JSONObject json, String code, String msg,
			String result, String resultnum) {
//		try {
//			result = replaceParamAfter(invokeAllMethod(result), json, returnrule);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			Assert.fail("反射执行方法失败", e.fillInStackTrace());
//		}
		String coderule = returnrule.get("code").toString();
		String messagerule = returnrule.get("message").toString();
		String datarule = returnrule.get("_data_").toString();
		String tmpcode = getJsonReturn(coderule, json).toString();
		String tmpmsg = getJsonReturn(messagerule, json).toString();
		Object jsonData = getJsonReturn(datarule, json);
		Object jsonResult = null;
		String resultStr;
		if (!isStrEmpty(code) && !tmpcode.equals(code)) {
			Reporter.log("接口返回信息:" + json.toString());
			Assert.fail("返回的状态码：" + tmpcode + "与预期的状态码:" + code + "不一致");
		} else {
			if (!isStrEmpty(msg)) {
				if (null == tmpmsg) {
					Reporter.log("接口返回信息:" + json.toString());
					Assert.fail("接口测试失败。ecpected message:" + msg + ",but actrual message:" + tmpmsg);
				} else if (!tmpmsg.contains(msg)) {
					Reporter.log("接口返回信息:" + json.toString());
					Assert.fail("接口测试失败。ecpected message:" + msg + ",but actrual message:" + tmpmsg);
				}
			}
			// 接口返回参数规则不定：有时不返回result，有时返回result,有时候data为jsonarray有时候data为JSONobject
			// if (jsonData instanceof JSONArray){
			// jsonResult = jsonData;
			// }
			jsonResult = getJsonResult(jsonData);
			if (jsonResult instanceof JSONObject) {
				resultStr = ((JSONObject) jsonResult).toString();
				if (resultStr.equals("{}")) {
					if (!resultnum.equals("") && !resultnum.equals("0")) {
						Reporter.log("接口返回信息:" + json.toString());
						Assert.fail("返回数据个数" + 0 + "与预期" + resultnum + "不一致");
					}
				}
				// if (isStrEmpty(msg)) {
				// String [] tmp2 = Paras.split(",");
				// if (tmp2.length != ((JSONObject)jsonResult).size()) {
				// Reporter.log("接口返回信息:"+json.toString());
				// Assert.fail("返回数据参数个数" + ((JSONObject)jsonResult).size() +
				// "与预期" + tmp2.length + "不一致");
				// }
				// }
				else {
					interfaceParamsCheck2(json, jsonResult, result,returnrule);
				}
			} else if (jsonResult instanceof JSONArray) {
				resultStr = String.valueOf(((JSONArray) jsonResult).size());
				// if (JSON.parse(Paras) instanceof JSONObject) {
				// JSONObject myJsonObject = JSON.parseObject(Paras);
				// // 通过返回数据数组大小得出数据个数。但如果只显示了一页就有问题。所以应该通过totalcount判断，但目前这个参数有问题。所以暂时这样处理
				// if (jsonData instanceof JSONObject) {
				// if (Integer.parseInt(resultStr) >= 1000
				// && ((JSONObject) jsonData)
				// .containsKey("totalCount")) {
				// resultStr = ((JSONObject) jsonData)
				// .getString("totalCount");
				// }
				// if (Paras.contains("pageNo")
				// && ((JSONObject) jsonData).containsKey("pageNo")) {
				// int count = ((JSONObject) jsonData)
				// .getIntValue("totalCount");
				// int psize = ((JSONObject) jsonData)
				// .getIntValue("pageSize");
				// int pnum = ((JSONObject) jsonData)
				// .getIntValue("pageNo");
				// if (count / psize + 1 < myJsonObject
				// .getIntValue("pageNo")) {
				// if (pnum != count / psize + 1
				// && pnum != myJsonObject
				// .getIntValue("pageNo")) {
				// Reporter.log("接口返回信息:" + json.toString());
				// Assert.fail("返回的pageno" + pnum + "与预期" + count
				// / psize + 1 + "不一致;");
				// }
				// } else {
				// if (pnum != myJsonObject.getIntValue("pageNo")) {
				// Reporter.log("接口返回信息:" + json.toString());
				// Assert.fail("返回的pageno"
				// + ((JSONObject) jsonData)
				// .getString("pageNo") + "与预期"
				// + myJsonObject.getString("pageNo")
				// + "不一致;");
				// }
				// }
				// }
				// if (Paras.contains("pageNumber")
				// && ((JSONObject) jsonData)
				// .containsKey("pageNumber")) {
				// int count = ((JSONObject) jsonData)
				// .getIntValue("totalCount");
				// int psize = ((JSONObject) jsonData)
				// .getIntValue("pageSize");
				// int pnum = ((JSONObject) jsonData)
				// .getIntValue("pageNumber");
				// if (count / psize + 1 < myJsonObject
				// .getIntValue("pageNumber")) {
				// if (pnum != count / psize + 1
				// && pnum != myJsonObject
				// .getIntValue("pageNumber")) {
				// Reporter.log("接口返回信息:" + json.toString());
				// Assert.fail("返回的pageNumber" + pnum + "与预期"
				// + count / psize + 1 + "不一致;");
				// }
				// } else {
				// if (pnum != myJsonObject.getIntValue("pageNumber")) {
				// Reporter.log("接口返回信息:" + json.toString());
				// Assert.fail("返回的pageNumber"
				// + ((JSONObject) jsonData)
				// .getString("pageNumber")
				// + "与预期"
				// + myJsonObject.getString("pageNumber")
				// + "不一致;");
				// }
				// }
				// }
				// if (Paras.contains("pageSize")
				// && ((JSONObject) jsonData).containsKey("pageSize")) {
				// String size = myJsonObject.getString("pageSize");
				// String pasize = ((JSONObject) jsonData)
				// .getString("pageSize");
				// if (size.equals("0")) {
				// if (!pasize.equals("1000")) {
				// Reporter.log("接口返回信息:" + json.toString());
				// Assert.fail("返回的pageSize" + pasize
				// + "与预期1000不一致;");
				// }
				// } else {
				// if (!pasize.equals(size)) {
				// Reporter.log("接口返回信息:" + json.toString());
				// Assert.fail("返回的pageSize" + pasize + "与预期"
				// + size + "不一致;");
				// }
				// }
				// }
				// }
				//
				// }
				// else if (JSON.parse(Paras) instanceof JSONArray){
				// }
				// else {
				//
				// }
				if (!isStrEmpty(resultnum)) {
					if (!resultStr.equals(resultnum)) {
						Reporter.log("接口返回信息:" + json.toString());
						Assert.fail("接口调用成功，但返回数据条数" + resultStr + "与期望条数:" + resultnum + "不一致");
					}
				}
				if (Integer.parseInt(resultStr) > 0) {
					if (!isStrEmpty(result)) {
						// for (Object o : (JSONArray)jsonResult) {
						// interfaceParamsCheck(json, o, msg);
						// }
						interfaceParamsCheck2(json, jsonResult, result,returnrule);
					}
				} else if (Integer.parseInt(resultStr) == 0 && !isStrEmpty(result)) {
					Reporter.log("接口返回信息:" + json.toString());
					Assert.fail("返回0条数据,不存在与预期result的对比");
				}
			} else {
				if (jsonResult == null) {
					resultStr = null;
				} else {
					resultStr = jsonResult.toString();
				}
				if (!isStrEmpty(result)) {
					String strs[] = result.split(";");
					for (String ss : strs) {
						String s = ss;
						try {
							s = replaceParamAfter(invokeAllMethod(ss), json, returnrule);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							Assert.fail("反射执行方法失败", e.fillInStackTrace());
						}
						if (s.contains("(") && s.endsWith(")")) {
							Boolean founded = false;
							String tmparr[] = s.split("\\(", 2);
							String method = tmparr[0].trim();
							String tmps = tmparr[1].substring(0, tmparr[1].lastIndexOf(")"));
							Object param[];
							Class<?>[] cArg = null;
							if (tmps.trim().isEmpty()) {
								param = null;
							} else {
								param = splitSpecific(tmps);
								cArg = new Class[param.length];
								for (int i = 0; i < cArg.length; i++) {
									cArg[i] = String.class;
								}
							}
							
								List<Class> clslist = GetAllClassHandler.getAllObjectCompare();
								for1:
								for (Class cls : clslist) {										
									Method m1 = null;
									Object o = null;
									try {
										m1 = cls.getDeclaredMethod(method, cArg);
									} catch (NoSuchMethodException | SecurityException e) {
										// TODO Auto-generated catch block
										try {
											m1 = cls.getDeclaredMethod(method, String[].class);
											param = new Object[] { param };
										} catch (NoSuchMethodException | SecurityException e1) {
											// TODO Auto-generated catch block
											continue for1;
										}
									}
									founded = true;
									m1.setAccessible(true);
									try {
										o = m1.invoke(cls.newInstance(), param);
									} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
											| InstantiationException e) {
										// TODO Auto-generated catch block
										if (e instanceof InvocationTargetException) {
											if (((InvocationTargetException) e).getTargetException().getClass().equals(AssertionError.class)) {
//												Assert.fail("不满足条件:" + ss + "，接口测试失败");
												Assert.fail("不满足条件:" + ss + "，接口测试失败", ((InvocationTargetException) e).getTargetException());
											}
										}
										else {
											StringWriter sw = new StringWriter();
											e.printStackTrace(new PrintWriter(sw, true));
											Assert.fail("反射执行方法失败" + "\r\n" + sw.toString());
										}
									}
									if(null == o) {
//										方法为void
									}
									else{
										if (o instanceof TResult) {
											Boolean tmpBol = ((TResult) o).getResult();
											String errdata = ((TResult) o).getErrData();
											if (!tmpBol) {
												if (null != errdata && !errdata.isEmpty()) {
													Assert.fail("接口返回数据中存在数据" + errdata + "不满足条件:" + ss + "，接口测试失败");
												} else {
													Assert.fail("接口返回数据中存在数据" + jsonResult.toString() + "不满足条件:" + ss + "，接口测试失败");
												}
											}
										} else if (o instanceof Boolean) {
											Boolean tmpBol = (Boolean) o;
											if (!tmpBol) {
												Assert.fail("接口返回数据中存在数据" + jsonResult.toString() + "不满足条件:" + ss + "，接口测试失败");
											}
										}
									}
									break for1;
								}
								if (!founded) {
									Assert.fail("断言失败，找不到满足条件的方法:"+method+Arrays.toString(cArg));
								}
						} else if (!resultStr.contains(s)) {
							Reporter.log("接口返回信息:" + json.toString());
							Assert.fail("接口调用成功，但返回result:" + resultStr + "不包含" + ss);
						}
					}

				}
			}
			// tmpmsg = json.get("message").toString();
		}
	}

	/**
	 * 接口返回参数检查
	 * 
	 * @param json
	 *            接口返回json
	 * @param jsonResult
	 *            接口返回result
	 * @param result
	 *            期望result(excel中传入)
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 */
	public static void interfaceParamsCheck2(JSONObject json, Object jsonResult, String msg, Map<String, String> returnrule) {
		String[] msgArr = msg.split(";");
		Reporter.log("接口返回信息:" + json.toString());
		for (String ss : msgArr) {
			String msgStr = ss;
			try {
				msgStr = replaceParamAfter(invokeAllMethod(ss), json, returnrule);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Assert.fail("反射执行方法失败", e.fillInStackTrace());
			}
			if (msgStr.contains("(") && msgStr.endsWith(")")) {
				String tmparr[] = msgStr.split("\\(", 2);
				String method = tmparr[0].trim();
				Boolean founded = false;
				String tmps = tmparr[1].substring(0, tmparr[1].lastIndexOf(")"));
				Object param[];
				Class<?>[] cArg = null;
				if (tmps.trim().isEmpty()) {
					param = null;
				} else {
//					if (method.equalsIgnoreCase("containsRs")) {
//						param = new String[] { tmps };
//						param = trimArr(param);
//					} else {
						param = splitSpecific(tmps);
//					}
					cArg = new Class[param.length];
					for (int i = 0; i < cArg.length; i++) {
						cArg[i] = String.class;
					}
				}
				List<Class> clslist = new ArrayList<>();
				if (method.startsWith("*")) {
					method = method.replaceFirst("\\*", "");
					clslist = GetAllClassHandler.getAllObjectCompare();
					for1:
						for (Class cls : clslist) {										
							Method m1 = null;
							Object o = null;
							try {
								m1 = cls.getDeclaredMethod(method, cArg);
							} catch (NoSuchMethodException | SecurityException e) {
								// TODO Auto-generated catch block
								try {
									m1 = cls.getDeclaredMethod(method, String[].class);
									param = new Object[] { param };
								} catch (NoSuchMethodException | SecurityException e1) {
									// TODO Auto-generated catch block
									continue for1;
								}
							}
							founded = true;
							m1.setAccessible(true);
							try {
								o = m1.invoke(cls.newInstance(), param);
							} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
									| InstantiationException e) {
								// TODO Auto-generated catch block
								if (e instanceof InvocationTargetException) {
									if (((InvocationTargetException) e).getTargetException().getClass().equals(AssertionError.class)) {
										Assert.fail("不满足条件:" + ss + "，接口测试失败", ((InvocationTargetException) e).getTargetException());
									}
								}
								else {
									StringWriter sw = new StringWriter();
									e.printStackTrace(new PrintWriter(sw, true));
									Assert.fail("反射执行方法失败" + "\r\n" + sw.toString());
								}							
							}
							if(null == o) {
//								方法为void
							}
							else{
								if (o instanceof TResult) {
									Boolean tmpBol = ((TResult) o).getResult();
									String errdata = ((TResult) o).getErrData();
									if (!tmpBol) {
										if (null != errdata && !errdata.isEmpty()) {
											Assert.fail("接口返回数据中存在数据" + errdata + "不满足条件:" + ss + "，接口测试失败");
										} else {
											Assert.fail("接口返回数据中存在数据" + jsonResult.toString() + "不满足条件:" + ss + "，接口测试失败");
										}
									}
								} else if (o instanceof Boolean) {
									Boolean tmpBol = (Boolean) o;
									if (!tmpBol) {
										Assert.fail("接口返回数据中存在数据" + jsonResult.toString() + "不满足条件:" + ss + "，接口测试失败");
									}
								}
							}
							break for1;
						}
					
				}
				else {
					if (jsonResult instanceof JSONArray) {
						clslist = GetAllClassHandler.getAllJsonArrayJsonCompare();
					}
					else if(jsonResult instanceof JSONObject) {
						clslist = GetAllClassHandler.getAllJsonObjectCompare();
					}
		
					for1:
					for (Class cls : clslist) {	
						Constructor<?> con = null;
						try {
							con = cls.getConstructor(String.class);
						} catch (NoSuchMethodException | SecurityException e1) {
							// TODO Auto-generated catch block
							StringWriter sw = new StringWriter();
							e1.printStackTrace(new PrintWriter(sw, true));
							Assert.fail("反射执行方法失败" + "\r\n" + sw.toString());
						}
							Method m1 = null;
							Object o = null;
							try {
								m1 = cls.getDeclaredMethod(method, cArg);
							} catch (NoSuchMethodException | SecurityException e) {
								// TODO Auto-generated catch block
								try {
									m1 = cls.getDeclaredMethod(method, String[].class);
									param = new Object[] { param };
								} catch (NoSuchMethodException | SecurityException e1) {
									// TODO Auto-generated catch block
									continue for1;
								}
							}	
							
							founded = true;
							m1.setAccessible(true);
							try {
								o = m1.invoke(con.newInstance(jsonResult.toString()), param);
							} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
									| InstantiationException e) {
								// TODO Auto-generated catch block
								if (e instanceof InvocationTargetException) {
									if (((InvocationTargetException) e).getTargetException().getClass().equals(AssertionError.class)) {
										Assert.fail("不满足条件:" + ss + "，接口测试失败", ((InvocationTargetException) e).getTargetException());
									}
								}
								else {
									StringWriter sw = new StringWriter();
									e.printStackTrace(new PrintWriter(sw, true));
									Assert.fail("反射执行方法失败" + "\r\n" + sw.toString());
								}	
							}							
							if(null == o) {
//								方法为void
							}
							else{
								if (o instanceof TResult) {
									Boolean tmpBol = ((TResult) o).getResult();
									String errdata = ((TResult) o).getErrData();
									if (!tmpBol) {
										if (null != errdata && !errdata.isEmpty()) {
											Assert.fail("接口返回数据中存在数据" + errdata + "不满足条件:" + ss + "，接口测试失败");
										} else {
											Assert.fail("接口返回数据中存在数据" + jsonResult.toString() + "不满足条件:" + ss + "，接口测试失败");
										}
									}
								} else if (o instanceof Boolean) {
									Boolean tmpBol = (Boolean) o;
									if (!tmpBol) {
										Assert.fail("接口返回数据中存在数据" + jsonResult.toString() + "不满足条件:" + ss + "，接口测试失败");
									}
								}
							}
							break for1;
					}	
				}	
				if (!founded) {
					Assert.fail("断言失败，找不到满足条件的方法:"+method+Arrays.toString(cArg));
				}
			} else {
				if (jsonResult instanceof JSONObject) {
					if (!jsonResult.toString().contains(msgStr)) {
						Assert.fail("接口返回数据中存在数据" + jsonResult.toString() + "不包含:" + ss + "，接口测试失败");
					}
				} else if (jsonResult instanceof JSONArray) {
					for (Object o : (JSONArray) jsonResult) {
						if (!((JSONObject) o).toString().contains(msgStr)) {
							Assert.fail("接口返回数据" + jsonResult.toString() + "中的:" + ((JSONObject) o).toString() + "不包含"
									+ ss + "，接口测试失败");
						}
					}
				}

			}
		}
	}

	/**
	 * 判断STRING中是不是时间类型
	 * 
	 * @param str
	 *            String
	 * @param formatStr
	 *            时间格式
	 * @return boolean
	 */
	public static boolean isValidDate(String str, String formatStr) {
		boolean convertSuccess = true;
		// 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
		SimpleDateFormat format = new SimpleDateFormat(formatStr);
		try {
			// 设置lenient为false.
			// 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
			format.setLenient(false);
			format.parse(str);
		} catch (ParseException e) {
			// e.printStackTrace();
			// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
			convertSuccess = false;
		}
		return convertSuccess;
	}

	/**
	 * 去掉数组中字符串中左右的空格
	 * 
	 * @param arr
	 * @return Object[] 处理后的数组
	 */
	public static Object[] trimArr(Object[] arr) {
		for (int i = 0; i < arr.length; i++) {
			arr[i] = arr[i].toString().trim();
		}
		return arr;
	}

	/**
	 * 将参数拆分（主要用于应对参数中有组合参数的情况，如a,"b1,b2,b3",c）
	 * 
	 * @param str
	 * @return String[] 处理后的数组
	 */
	public static Object[] splitSpecific(String str) {
		Object[] param;
		 if (str.startsWith("[") && str.endsWith("]")) {
			 if (!ObjectCompare.isJsonArray(str)) {
				 String s1[] = str.split("\\],\\[");
				 for (int i = 0; i < s1.length; i++) {
					 s1[i] = s1[i].replaceAll("\\[", "").replaceAll("\\]", "")
					 .trim();
				 }
				 return s1;
			 }
			 else {
				 String [] s = {str};
				 return  s;
			 }		
		 } 
		 else if (str.startsWith("{") && str.endsWith("}")) {
			 if (!ObjectCompare.isJsonObject(str)) {
				 String s1[] = str.split("\\},\\{");
				 for (int i = 0; i < s1.length; i++) {
					 s1[i] = s1[i].replaceAll("\\{", "").replaceAll("\\}", "")
					 .trim();
				 }
				 return s1;
			 }
			 else {
				 String [] s = {str};
				 return  s;
			 }		
		 } 
		 else if (str.startsWith("'") && str.endsWith("'")) {
			String s1[] = str.split("\',\'");
			for (int i = 0; i < s1.length; i++) {
				s1[i] = s1[i].replaceAll("\'", "").trim();
			}
			return s1;
		}

		else if (str.contains(",\"") || str.contains("\",")) {
			if (!ObjectCompare.isJsonObject("{"+str+"}")) {
				String s1[] = str.replaceAll(",\"", "\",").split("\",");
				for (int i = 0; i < s1.length; i++) {
					s1[i] = s1[i].replaceAll("\"", "").trim();
				}
				return s1;
			}
			else {
				String [] s = {str};
				return  s;
			}
		} else {
			param = str.split(",");
			param = trimArr(param);
			return param;
		}
	}

	/**
	 * 返回字符串str1中子串str2的个数
	 * 
	 * @param str1
	 * @param str2
	 * @return int
	 */
	public static int subCounter(String str1, String str2) {

		int counter = 0;
		for (int i = 0; i <= str1.length() - str2.length(); i++) {
			if (str1.substring(i, i + str2.length()).equalsIgnoreCase(str2)) {
				counter++;
			}
		}
		return counter;
	}

	// /**
	// * php 获取Json的data信息
	// *
	// * @param json
	// * JSONObject
	// * @return JSONObject
	// */
	// public static Object getJsonData(JSONObject json) {
	// Object jsondata = json;
	// while (((JSONObject) jsondata).containsKey("data")) {
	// jsondata = ((JSONObject) jsondata).get("data");
	// if (!(jsondata instanceof JSONObject)) {
	// break;
	// }
	// }
	// return jsondata;
	// // while (json.containsKey("data")) {
	// // json = json.getJSONObject("data");
	// // }
	// // return json;
	// }
	/**
	 * 解析json结果
	 * 
	 * @param path
	 *            json寻址路径
	 * @param json
	 *            被查询的json数据
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Object getJsonReturn(String path, Object jsonreturn) {
		String oldpath = path;
		String[] paths = path.split("\\.");
		for (int i = 0; i < paths.length; i++) {
			if (null == jsonreturn) {
				break;
			}
			else if (jsonreturn instanceof JSONArray) {
				if (paths[i].startsWith("[") && paths[i].endsWith("]")) {
					String s = paths[i].replaceAll("\\[", "").replaceAll("\\]", "");
					if (s.isEmpty()) {
						jsonreturn = ((JSONArray)jsonreturn).toJavaList(Object.class);
					}
					else if (ObjectCompare.isNumeric(s)) {
						int index = Integer.parseInt(s);
						if ( ((JSONArray)jsonreturn).size() < index+1) {
							Assert.fail("当前寻址数据:"+jsonreturn.toString()+"json寻址路径:"+oldpath+"获取获取数组中第几条数据时index超过数组可以取到的条数");
						}
						jsonreturn = ((JSONArray)jsonreturn).get(index);
					}
					else {
						Assert.fail("当前寻址数据:"+jsonreturn.toString()+"json寻址路径:"+oldpath+"获取获取数组中第几条数据时必须是非负整数或者空，如[0]获取位置为0的数据，p获取所有数据");
					}
				}
			}
			else if (jsonreturn instanceof JSONObject){
				if (!((JSONObject) jsonreturn).containsKey(paths[i])) {
					Assert.fail("当前寻址数据:"+jsonreturn.toString()+"找不到此寻址路径的json数据"+oldpath);
				}
				jsonreturn = ((JSONObject) jsonreturn).get(paths[i]);
			}
			else if (jsonreturn instanceof List) {
				List<Object> l = new ArrayList<>();
				for (Object o : (List<Object>)jsonreturn) {
					l.add(getJsonReturn(path, o));
				}
				jsonreturn = l;
			}
			if (paths[i].startsWith("[") && paths[i].endsWith("]")) {
				path = path.replaceFirst(paths[i].replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"\\.", "");
			}
			else {
				path = path.replaceFirst(paths[i]+"\\.", "");
			}
		}
		if (jsonreturn == null) {
			jsonreturn = "";
		}
		return jsonreturn;
	}
	// /**
	// * php 获取Json的message信息
	// *
	// * @param json
	// * JSONObject
	// * @return String
	// */
	// public static String getJsonMessage(JSONObject json) {
	// String message = null;
	// if (json.containsKey("data") && json.get("data") != null) {
	// while (json.containsKey("data")) {
	// if (json.containsKey("message")) {
	// message = json.getString("message");
	// } else if (json.getString("data").contains("\"message\"")) {
	// if (json.get("data") instanceof JSONObject
	// && json.getJSONObject("data")
	// .containsKey("message")) {
	// message = json.getJSONObject("data").getString(
	// "message");
	// }
	// if (json.get("data") instanceof JSONArray
	// && json.getJSONArray("data").getJSONObject(0)
	// .containsKey("message")) {
	// message = json.getJSONArray("data").getJSONObject(0)
	// .getString("message");
	// }
	// }
	// if (json.get("data") instanceof JSONObject) {
	// json = json.getJSONObject("data");
	// } else {
	// break;
	// }
	// }
	// } else {
	// message = json.getString("message");
	// }
	// return message;
	// }
	//
	// /**
	// * php 获取Json的code信息
	// *
	// * @param json
	// * JSONObject
	// * @return String
	// */
	// public static String getJsonCode(JSONObject json) {
	// String code = null;
	// if (json.containsKey("data") && json.get("data") != null
	// && json.getString("data").contains("\"code\"")) {
	// while (json.containsKey("data")) {
	// if (json.get("data") instanceof JSONObject) {
	// code = json.getString("code");
	// json = json.getJSONObject("data");
	// } else if (json.get("data") instanceof JSONArray) {
	// code = json.getString("code");
	// break;
	// }
	// }
	// } else {
	// code = json.getString("code");
	// }
	// return code;
	// }

	/**
	 * 获得json result
	 * 
	 * @param 返回json
	 *            JSONObject
	 * @return String
	 */
	public static Object getJsonResult(Object jsonData) {
		Object jsonResult = null;
		if (jsonData instanceof JSONObject) {
			if (((JSONObject) jsonData).containsKey("result")) {
				jsonResult = ((JSONObject) jsonData).get("result");
			} else {
				jsonResult = jsonData;
			}
		} else {
			jsonResult = jsonData;
		}
		return jsonResult;
	}

	public static Exception classForName(String cls) {
		Exception ex = null;
		try {
			Class.forName(cls);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			ex = e;
		}
		return ex;
	}
	//
	// /**
	// * 执行复查场景测试
	// * @param cls 类名
	// * @param assertStr 断言语句
	// */
	// public static void duplicateSceneTest(String cls, String assertStr) {
	// String tmp[] = cls.split("\\.");
	// String ss = "";
	// for (int i = 0; i < tmp.length - 1; i++) {
	// ss += "/" + tmp[i];
	// }
	// String clspath = CommonUtils.getFilePath("/src" + ss);
	// FileUtils f = new FileUtils();
	// String newfilename = tmp[tmp.length - 1] + "_invoke_"
	// + System.currentTimeMillis();
	// f.createFile(clspath + "\\" + newfilename + ".java",
	// "package " + cls.substring(0, cls.lastIndexOf(".")) + ";"
	// + "\r" + "import org.testng.Assert;" + "\r"
	// + "public class " + newfilename + " {" + "\r"
	// + "public static void main(String[] args) {" + "\r"
	// + assertStr + ";" + "\r" + "}" + "\r" + "}", "UTF-8");
	// try {
	// String cmdStr = "javac -classpath D:/workspace/autotest_demo/libs/testng.jar
	// "
	// + clspath + "\\" + newfilename + ".java";
	// Runtime.getRuntime().exec(cmdStr);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// String method = "main";
	// String clsfile = cls.substring(0, cls.lastIndexOf(".")) + "."
	// + newfilename;
	// try {
	// while (classForName(clsfile) == null) {
	// Thread.sleep(1000);
	// }
	// Class<?> callcls = Class.forName(clsfile);
	// Method m1 = callcls.getDeclaredMethod(method, String[].class);
	// m1.invoke(callcls.newInstance(), new Object[] { new String[] {} })
	// .toString();
	// } catch (Exception e) {
	// if (e.getCause().toString().contains("AssertionError")) {
	// Assert.fail(e.getCause().toString());
	// } else {
	// Assert.fail("反射方式执行逻辑处理函数" + method + "失败");
	// }
	// } finally {
	// f.delFile(clspath + "\\" + newfilename + ".java");
	// f.delFile(clspath + "\\" + newfilename + ".class");
	// }
	// }

	private static String bracket = "BRACKET";

	/**
	 * 执行字符串中所有需要执行的方法
	 * @param s
	 * @param clslist
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws InstantiationException
	 */
	public static String invokeAllMethod(String s) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException {
		List<Class> clslist = GetAllClassHandler.getAllClass();
		for (Class cls : clslist) {
			s = invokeMethod(s, cls);
		}
		return s;
	}
	/**
	 * 反射执行方法
	 * 
	 * @param s 需要执行方法的字符串
	 * @param cls
	 *            执行哪个类中方法
	 * @return 执行方法后的字符串
	 * @throws InstantiationException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public static String invokeMethod(String s, Class<?> cls)
			throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException {
		StackHashMap<Integer, String> sh = new StackHashMap<Integer, String>();
		int count = 0;
		String tmpstr = s;
//		Method ms[] = getAllMethodsList(cls);
		Method ms[] = cls.getDeclaredMethods();
		Set<String> set = new HashSet<String>();
		for (int i = 0; i < ms.length; i++) {
			set.add(ms[i].getName());
		}
		while (!s.isEmpty()) {
			// 取字符串首字母
			String character = s.substring(0, 1);
			// 剩余的字符串
			s = s.substring(1);
			if (character.equals("(")) {
				sh.push(count, character);
			} else if (character.equals(")")) {
				if (sh.isEmpty())
					break;
				int index = sh.peekKey();
				sh.pop();
				String tmp = null;
				String method = getMethod(tmpstr.substring(0, index));
				if (!set.contains(method)) {
					count++;
					continue;
				}
				String paramsstr = tmpstr.substring(index + 1, count);

				if (paramsstr.contains("{") && paramsstr.contains("}")) {
					tmp = paramsstr.substring(paramsstr.indexOf("{") + 1, paramsstr.lastIndexOf("}"));
					paramsstr = paramsstr.substring(0, paramsstr.indexOf("{") + 1) + bracket
							+ paramsstr.substring(paramsstr.lastIndexOf("}"));
				} else if (paramsstr.contains("[") && paramsstr.contains("]")) {
					tmp = paramsstr.substring(paramsstr.indexOf("[") + 1, paramsstr.lastIndexOf("]"));
					paramsstr = paramsstr.substring(0, paramsstr.indexOf("[") + 1) + bracket
							+ paramsstr.substring(paramsstr.lastIndexOf("]"));
				}
				Object parammeters[] = splitSpecific(paramsstr);
				for (int i = 0; i < parammeters.length; i++) {
					String pm = parammeters[i].toString();
					if (pm.contains(bracket)) {
						if (tmp.contains("\\")) {
							tmp = tmp.replaceAll("\\\\", "\\\\\\\\");
						}
						parammeters[i] = pm.replaceAll(replaceSpecialChar(bracket), tmp);
					}
				}
				parammeters = trimArr(parammeters);
				String invokeMethod = method + tmpstr.substring(index, count + 1);
				Class<?>[] cArg = null;
				if (parammeters.length == 1 && parammeters[0].toString().isEmpty()) {

				} else {
					cArg = new Class[parammeters.length];
					for (int j = 0; j < cArg.length; j++) {
						cArg[j] = String.class;
					}
				}
				// InterfaceUtils inter = new InterfaceUtils();
				// Class<?> cls = InterfaceUtils.class;
				Method m1 = null;
				try {
					m1 = getMethod(cls, method, cArg);
//					cls.getDeclaredMethod(method, cArg);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}
				Object tmpresult = null;
				m1.setAccessible(true);
				if (cArg == null) {
					tmpresult = m1.invoke(cls.newInstance());
				} else {
					tmpresult = m1.invoke(cls.newInstance(), parammeters);
				}
				String reslutStr;
				reslutStr = tmpresult == null ? ""
						: tmpresult instanceof Boolean ? String.valueOf(tmpresult) : tmpresult.toString();
				tmpstr = StringUtils.replaceOnce(tmpstr, invokeMethod, reslutStr);
				count += reslutStr.length() - invokeMethod.length();
			}
			count++;
			continue;
		}
		return tmpstr;
	}

	/**
	 * 反射执行字符串中方法
	 * 
	 * @param s
	 *            待执行其中方法的字符串
	 * @param cls
	 *            执行哪个类的方法
	 * @param clsinstance
	 *            反射执行该类方法的实例
	 * @return
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public static String invokeMethod(String s, Class<?> cls, Object clsinstance)
			throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		StackHashMap<Integer, String> sh = new StackHashMap<Integer, String>();
		// Stack<String> left=new Stack<String>();
		int count = 0;
		String tmpstr = s;
//		Method ms[] = getAllMethodsList(cls);
		Method ms[] = cls.getDeclaredMethods();
		Set<String> set = new HashSet<String>();
		for (int i = 0; i < ms.length; i++) {
			set.add(ms[i].getName());
		}
		while (!s.isEmpty()) {
			// 取字符串首字母
			String character = s.substring(0, 1);
			// 剩余的字符串
			s = s.substring(1);
			if (character.equals("(")) {
				sh.push(count, character);
			} else if (character.equals(")")) {
				if (sh.isEmpty())
					break;
				int index = sh.peekKey();
				String tmp = null;
				String method = getMethod(tmpstr.substring(0, index));
				if (!set.contains(method)) {
					count++;
					continue;
				}
				String paramsstr = tmpstr.substring(index + 1, count);
				if (paramsstr.contains("{") && paramsstr.contains("}")) {
					tmp = paramsstr.substring(paramsstr.indexOf("{") + 1, paramsstr.lastIndexOf("}"));
					paramsstr = paramsstr.substring(0, paramsstr.indexOf("{") + 1) + bracket
							+ paramsstr.substring(paramsstr.lastIndexOf("}"));
				} else if (paramsstr.contains("[") && paramsstr.contains("]")) {
					tmp = paramsstr.substring(paramsstr.indexOf("[") + 1, paramsstr.lastIndexOf("]"));
					paramsstr = paramsstr.substring(0, paramsstr.indexOf("[") + 1) + bracket
							+ paramsstr.substring(paramsstr.lastIndexOf("]"));
				}
				Object parammeters[] = splitSpecific(paramsstr);
				for (int i = 0; i < parammeters.length; i++) {
					String pm = parammeters[i].toString();
					if (pm.contains(bracket)) {
						if (tmp.contains("\\")) {
							tmp = tmp.replaceAll("\\\\", "\\\\\\\\");
						}
						parammeters[i] = pm.replaceAll(replaceSpecialChar(bracket), tmp);
					}
				}
				parammeters = trimArr(parammeters);
				String invokeMethod = method + tmpstr.substring(index, count + 1);
				Class<?>[] cArg = null;
				if (parammeters.length == 1 && parammeters[0].toString().isEmpty()) {

				} else {
					cArg = new Class[parammeters.length];
					for (int j = 0; j < cArg.length; j++) {
						cArg[j] = String.class;
					}
				}
				Method m1 = null;
				try {
					m1 = getMethod(cls, method, cArg);
//					m1 = cls.getDeclaredMethod(method, cArg);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}
				Object tmpresult = null;
				m1.setAccessible(true);
				if (cArg == null) {
					tmpresult = m1.invoke(clsinstance);
				} else {
					tmpresult = m1.invoke(clsinstance, parammeters);
				}
				String reslutStr;
				reslutStr = tmpresult == null ? ""
						: tmpresult instanceof Boolean ? String.valueOf(tmpresult) : tmpresult.toString();
				tmpstr = StringUtils.replaceOnce(tmpstr, invokeMethod, reslutStr);
				count += reslutStr.length() - invokeMethod.length();
			}
			count++;
			continue;
		}
		return tmpstr;
	}

	/**
	 * 是否是字母、数字、下划线
	 * 
	 * @param str
	 * @return
	 */
	public static Boolean isMethodStr(String str) {

		Boolean bl = false;
		Pattern pt = Pattern.compile("[0-9a-zA-Z_]+");
		Matcher mt = pt.matcher(str);
		if (mt.matches()) {
			bl = true;
		}
		return bl;
	}

	/**
	 * 获得字符串中方法
	 * 
	 * @param str
	 * @return
	 */
	public static String getMethod(String str) {
		String method = "";
		while (!str.isEmpty()) {
			String lastchar = str.substring(str.length() - 1, str.length());
			// 剩余的字符串
			str = str.substring(0, str.length() - 1);
			if (!isMethodStr(lastchar)) {
				break;
			} else {
				method = lastchar + method;
			}
		}
		return method;
	}

	/**
	 * 检查断言会否正确
	 * 
	 * @param str
	 *            传入断言的字符串
	 * @throws ScriptException
	 */
	public static void checkAssert(String str) throws ScriptException {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("js");
		Object result = engine.eval(str);
		Assert.assertTrue((Boolean) result, "断言结果不正确:" + str);
	}
	/** 
	 * 转义正则特殊字符 （$()*+.[]?\^{},|） 
	 *  
	 * @param keyword 
	 * @return 
	 */  
	public static String escapeExprSpecialWord(String keyword) {  
	    if (StringUtils.isNotBlank(keyword)) {  
	        String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };  
	        for (String key : fbsArr) {  
	            if (keyword.contains(key)) {  
	                keyword = keyword.replace(key, "\\" + key);  
	            }  
	        }  
	    }  
	    return keyword;  
	} 
/**
 * 调用接口前参数化替换
 * @param instr 
 * @return
 * @throws Exception
 */
	public String replaceParam(String instr,String method) throws ParamNotExistException {
		Pattern pattern = Pattern.compile("(?<=\\$\\{)[^}]*(?=\\})");
		Matcher matcher = pattern.matcher(instr);
		while(matcher.find()){
			String param = matcher.group();
			if (param.equalsIgnoreCase("method")) {
				instr = instr.replaceFirst("\\$\\{"+escapeExprSpecialWord(param)+"\\}", method);
			}
			else if (set.contains(param) || param.startsWith("_data_.") || param.startsWith("data.") || param.startsWith("code.") || param.startsWith("message.") || param.equalsIgnoreCase("jsonresult")) {
			
			}
			else if (parammap.containsKey(param)) {
				instr = instr.replaceFirst("\\$\\{"+escapeExprSpecialWord(param)+"\\}", parammap.get(param).toString());
			}
			else if (this.localparamsmap.containsKey(param)) {
				instr = instr.replaceFirst("\\$\\{"+escapeExprSpecialWord(param)+"\\}", localparamsmap.get(param).toString());
			}
			else {
				throw new ParamNotExistException("找不到参数:"+param);
			}
		}
		return instr;
	}
	/**
	 * 调用接口前参数化替换
	 * @param instr 
	 * @return
	 * @throws Exception
	 */
		public String replaceParam(String instr) throws ParamNotExistException {
			Pattern pattern = Pattern.compile("(?<=\\$\\{)[^}]*(?=\\})");
			Matcher matcher = pattern.matcher(instr);
			while(matcher.find()){
				String param = matcher.group();
				if (set.contains(param) || param.startsWith("_data_.") || param.startsWith("data.") || param.startsWith("code.") || param.startsWith("message.") || param.equalsIgnoreCase("jsonresult")) {
				
				}
				else if (parammap.containsKey(param)) {
					instr = instr.replaceFirst("\\$\\{"+escapeExprSpecialWord(param)+"\\}", parammap.get(param).toString());
				}
				else if (this.localparamsmap.containsKey(param)) {
					instr = instr.replaceFirst("\\$\\{"+escapeExprSpecialWord(param)+"\\}", localparamsmap.get(param).toString());
				}
				else {
					throw new ParamNotExistException("找不到参数:"+param);
				}
			}
			return instr;
		}
	/**
	 * 调用接口后将json结果替换给参数
	 * @param jsonstr 要替换的参数
	 * @param jsonresult 接口返回json
	 * @param returnrule 返回结果规则
	 * @return
	 */
	public static String replaceParamAfter(String jsonstr,JSONObject jsonresult,Map<String,String> returnrule){
		Pattern pattern = Pattern.compile("(?<=\\$\\{)[^}]*(?=\\})");
		Matcher matcher = pattern.matcher(jsonstr);
		while(matcher.find()){
			String param = matcher.group();
			if(set.contains(param)) {
				param = returnrule.get(param).toString();
				jsonstr = jsonstr.replaceFirst("\\$\\{"+escapeExprSpecialWord(param)+"\\}", getJsonReturn(param, jsonresult).toString());
			}
			if (param.startsWith("_data_.")) {
				param = param.replaceFirst("_data_\\.", returnrule.get("_data_").toString()+".");
				jsonstr = jsonstr.replaceFirst("_data_\\.", returnrule.get("_data_").toString()+".");
				jsonstr = jsonstr.replaceFirst("\\$\\{"+escapeExprSpecialWord(param)+"\\}", getJsonReturn(param, jsonresult).toString());
			}
			else if (param.startsWith("data.")) {
				jsonstr = jsonstr.replaceFirst("\\$\\{"+escapeExprSpecialWord(param)+"\\}", getJsonReturn(param, jsonresult).toString());
			}
			else if (param.startsWith("code.")) {
				param = param.replaceFirst("code\\.", returnrule.get("code").toString()+".");
				jsonstr = jsonstr.replaceFirst("code\\.", returnrule.get("code").toString()+".");
				jsonstr = jsonstr.replaceFirst("\\$\\{"+escapeExprSpecialWord(param)+"\\}", getJsonReturn(param, jsonresult).toString());
			}
			else if ( param.startsWith("message.")) {
				param = param.replaceFirst("message\\.", returnrule.get("message").toString()+".");
				jsonstr = jsonstr.replaceFirst("message\\.", returnrule.get("message").toString()+".");
				jsonstr = jsonstr.replaceFirst("\\$\\{"+escapeExprSpecialWord(param)+"\\}", getJsonReturn(param, jsonresult).toString());
			}
			else if (param.equalsIgnoreCase("jsonresult")) {
				jsonstr = jsonresult.toString();
			}
		}
		return jsonstr;
	}
	
	public static Boolean isMapContainsEqualsKey(Map<String,Object> m, String key) {
		Boolean bol = false;
		for (String k : m.keySet()) {
			if (k.contains(key)) {
				bol = true;
				break;
			}
		}
		return bol;
	}
	public static String findContainsKey(Map<String,Object> m, String keystr) {
		String key = "";
		for (String k : m.keySet()) {
			if (k.contains(keystr)) {
				key = k;
			}
		}
		return key;
	}
	/**
	 * 执行断言
	 * @param assertmap
	 */
	public void excAssert(Map<String, Object> assertmap) {
		String assertstr = assertmap.get(findContainsKey(assertmap, "assert")).toString();
		assertstr = replaceParam(assertstr);
		try {
			assertstr = invokeAllMethod(assertstr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Assert.fail("反射执行方法失败", e.fillInStackTrace());
		}
		try {
			checkAssert(assertstr);
		} catch (ScriptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Assert.fail("断言方法执行失败",e.fillInStackTrace());
		}
	}
	/**
	 * 执行sleep
	 * @param map
	 */
	public static void excSleep(Map<String, Object> map) {
		long sleeptime = Long.parseLong(map.get(findContainsKey(map, "sleep")).toString());
		try {
			Thread.sleep(sleeptime);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Assert.fail("断言方法执行失败",e.fillInStackTrace());
		}
	}
	/**
	 * 执行MQ
	 * @param testfilepath
	 * @param map
	 */
	public void excMq(String testfilepath,Map<String, Object> map) {
		
		final AtomicInteger count = new AtomicInteger();
		final Object[][] currentCaseTotaldata_mq = (Object[][]) map.get(findContainsKey(map, "mq"));
		 Vector<Thread> threads = new Vector<Thread>();  
		for (int j = 0; j < currentCaseTotaldata_mq.length; j++) {
			Thread t = new Thread(new Runnable() {
				@Override
				public void run() {
					count.incrementAndGet();
					int index = count.get() - 1;
					Object []mqarr = (Object[])currentCaseTotaldata_mq[index];
					String key = replaceParam(currentCaseTotaldata_mq[index][10].toString());								
					Map<Integer, Date> mq_timemap = new HashMap<Integer, Date>();	
					File filepath = getRelativePathFile(testfilepath.toString(), replaceParam(mqarr[7].toString()));	
					// rocketmq中发送消息
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					RockectMqProduce rmq = new RockectMqProduce(
							"autotest"+index+"_"+now("yyyyMMddHHmmss"), replaceParam(mqarr[0].toString()),
							"autotest_"+now());
					try {
						rmq.start();
						getRmqmap().add(rmq);
						//根据文件内容发送
						mq_timemap = rmq.sendMsgFromFile(filepath.toString(),replaceParam(mqarr[1].toString()), replaceParam(mqarr[2].toString()), replaceParam(mqarr[3].toString()),invokeAllMethod(replaceParam(mqarr[4].toString())),replaceParam(mqarr[5].toString()),Integer.parseInt(replaceParam(mqarr[6].toString())),Integer.parseInt(replaceParam(mqarr[8].toString())),Integer.parseInt(replaceParam(mqarr[9].toString())),0);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Assert.fail("插入MQ异常", e.fillInStackTrace());
					}
					InterfaceUtils.getMsg_map().put(key, mq_timemap);
				}
			});
			threads.add(t);
			t.start();
		}
		for (Thread iThread : threads) {  
		      try {  
		        // 等待所有线程执行完毕  
		        iThread.join();  
		      } catch (InterruptedException e) {  
		        e.printStackTrace();  
		      }  
		}	
	}
	/**
	 * 执行发送报文
	 * @param testfilepath
	 * @param map
	 */
	public void excSendmsg(String testfilepath,Map<String, Object> map) {
		final AtomicInteger count = new AtomicInteger();
		ThreadPoolExecutor pool = new ThreadPoolExecutor(

			    20,100,600,

			    TimeUnit.SECONDS, 

			    new ArrayBlockingQueue<Runnable>(5),

			    new ThreadPoolExecutor.CallerRunsPolicy());
		final Object[][] currentCaseTotaldata1 = (Object[][]) map.get(findContainsKey(map, "sendmsg"));				
		for (int j = 0; j < currentCaseTotaldata1.length; j++) {
			Runnable r = new Runnable() {
				@Override
				public void run() {
					count.incrementAndGet();
					int index = count.get() - 1;
					String sendMethod = replaceParam(currentCaseTotaldata1[index][0].toString().trim());
					String msgadd = replaceParam(currentCaseTotaldata1[index][1].toString().trim());
					String portstr = replaceParam(currentCaseTotaldata1[index][2].toString().trim());
					String sendtime = replaceParam(currentCaseTotaldata1[index][3].toString().trim());
					if (sendtime.contains("(") && sendtime.contains(")")) {
						try {
							sendtime = InterfaceUtils.invokeAllMethod(sendtime);
						} catch (IllegalArgumentException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							Assert.fail("反射执行方法失败",e.fillInStackTrace());
						} catch (IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							Assert.fail("反射执行方法失败",e.fillInStackTrace());
						} catch (InvocationTargetException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							Assert.fail("反射执行方法失败",e.fillInStackTrace());
						} catch (InstantiationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							Assert.fail("反射执行方法失败",e.fillInStackTrace());
						}

					}
					String timestamp = replaceParam(currentCaseTotaldata1[index][4].toString().trim());
					int internal = Integer.parseInt(replaceParam(currentCaseTotaldata1[index][5].toString().trim()));
					String msg = replaceParam(currentCaseTotaldata1[index][6].toString().trim());
					String startnum = replaceParam(currentCaseTotaldata1[index][7].toString().trim());
					String sendcount = replaceParam(currentCaseTotaldata1[index][8].toString().trim());
					String key = replaceParam(currentCaseTotaldata1[index][9].toString().trim());
					List<String> msglist = new ArrayList<String>();
					if (msg.endsWith(".txt")) {
						try {
							List<String> list = FileUtils.readLines(getRelativePathFile(testfilepath, msg), "UTF-8");
							if (startnum.isEmpty()) {
								startnum = "1";
							}
							int tmpint = Integer.parseInt(startnum)-1;
							int count = 0;
							if (sendcount.isEmpty()) {
								count = list.size() - tmpint;
							}
							else {
								count = Integer.parseInt(sendcount);
							}
							for (int k = tmpint; k < tmpint+count; k++) {
								msglist.add(list.get(k));
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							Assert.fail("读取报文文件失败");
						}
					}
					else {
						msglist = Arrays.asList(msg.split("\n"));
					}
					MsgSend ms = new MsgSend();
					Map<Integer, Date> m_samrt = new HashMap<Integer, Date>();
					//发送mqtt报文时，地址填url;模式(例如http:tx.huoyunren.com;1。模式：1为固定式，0为便携式)，端口填topic;imei(例如topic_gps_location;107015090000007)。
					if (sendMethod.equals("sendMqttMsg")) {
//						try {
//							m_samrt = ms.sendMqttMsg(msgadd.split(";")[0], portstr.split(";")[0], msglist, portstr.split(";")[1], msgadd.split(";")[1],sendtime, timestamp, internal);
//						} catch (IOException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}
					}
					else {
						int port = Integer.parseInt(portstr);
						if (sendMethod.equals("sendMsg")) {
							m_samrt = ms.sendMsg(msgadd, port, msglist, sendtime, timestamp, internal);
						}
						else if (sendMethod.equals("sendString")) {
							m_samrt = ms.sendString(msgadd, port, msglist, sendtime, timestamp, internal);
						}
						else if (sendMethod.equals("sendStringOnAndOff")) {
							m_samrt = ms.sendStringOnAndOff(msgadd, port, msglist, sendtime,timestamp, internal);
						}
						else if (sendMethod.equals("sendUDP")) {
							try {
								m_samrt = ms.sendUDP(msgadd, port, msglist, sendtime, timestamp, internal);
							} catch (SocketException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					InterfaceUtils.getMsg_map().put(key, m_samrt);
				}
			};
			pool.execute(r);
		}
		pool.shutdown();// 只是不能再提交新任务，等待执行的任务不受影响
		try {
			boolean loop = true;
			do { // 等待所有任务完成
				loop = !pool.awaitTermination(10, TimeUnit.MINUTES); // 阻塞，直到线程池里所有任务结束
			} while (loop);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 执行mysql
	 * @param testfilepath
	 * @param map
	 */
	public void excMysql (String testfilepath,Map<String, Object> map) {

		Object [][] currentCaseTotaldata = (Object[][]) map.get(findContainsKey(map, "mysql"));
		for (int j = 0; j < currentCaseTotaldata.length; j++) {
			String resultnum = replaceParam(currentCaseTotaldata[j][4].toString().trim());
			String sqlsheet = replaceParam(currentCaseTotaldata[j][5].toString().trim());
			String checkkey = replaceParam(currentCaseTotaldata[j][6].toString().trim());
			String notcheckkey = replaceParam(currentCaseTotaldata[j][7].toString().trim());
			List<Map<String, String>> sqllist = new ArrayList<>();						
			try {
				if (sqlsheet.isEmpty()) {
					Assert.fail("请输入sql验证的期望结果");
				}
				else if (ObjectCompare.isJsonArray(sqlsheet)) {
					JSONArray ja = JSON.parseArray(sqlsheet);
					for (Object jo : ja) {
						if(!(jo instanceof JSONObject)) {
							Assert.fail("sql验证的JSONArray格式的期望结果格式不正确，请确认数组下都是JSONObject对象");
						}
						Map<String, String> m = JSONObject.parseObject(((JSONObject)jo).toJSONString(), new TypeReference<Map<String, String>>(){});
						sqllist.add(m);
					}
				}
				else {
					sqllist = DataRetrieveHandlers.getSqlResult(testfilepath, sqlsheet);
				}
				DataRetrieveHandlers.sqlExcute(j+1,replaceParam(currentCaseTotaldata[j][0].toString().trim()), replaceParam(currentCaseTotaldata[j][1].toString().trim()), replaceParam(currentCaseTotaldata[j][2].toString().trim()), invokeAllMethod(replaceParam(currentCaseTotaldata[j][3].toString().trim())),resultnum,sqllist,checkkey,notcheckkey,DataRetrieveHandlers.file);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Assert.fail("sql日志文件读写失败");
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Assert.fail("反射执行方法失败");
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Assert.fail("反射执行方法失败");
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Assert.fail("反射执行方法失败");
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Assert.fail("反射执行方法失败");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	/**
	 * 测试
	 * 
	 * @param filepath
	 *            测试数据文件
	 * @param arr
	 *            测试数据
	 */
	@SuppressWarnings("unchecked")
	public void excTest (String testfilepath, Object... arr) {
		localparamsmap = new HashMap<>();
		List<Map<String, Object>> returnlist = (List<Map<String, Object>>) arr[0];
		String testdesc = "";
		List<String> unexcIndexstr = new ArrayList<>();
		for (Map<String, Object> m :returnlist) {
			if (isMapContainsEqualsKey(m, "interface")) {
				List<Map<String, Object>> tmpl = (List<Map<String, Object>>)m.get(findContainsKey(m, "interface"));
				for (Map<String, Object> returnmap : tmpl) {
					LinkedHashMap<String, String> datamap = (LinkedHashMap<String, String>) returnmap.get("datamap");
					String checks = datamap.containsKey("check") ? datamap.get("check").toString() : "";
					if (!isStrEmpty(checks)) {
						String checkarr[] = checks.split(";");
						for (String checkstr : checkarr) {
							int checkindex = getCheckIndex(returnlist, checkstr);
							if (-1 == checkindex) {
								Assert.fail("找不到对应check:"+checkstr);
							}
							else {
								unexcIndexstr.add(checkstr);
							}
						}
					}
				}			
			}
		}
		for (Map<String, Object> m :returnlist) {
			int tmpindex = returnlist.indexOf(m);
			if (m.containsKey("testdesc")) {
				testdesc = m.get("testdesc").toString();
				continue;
			}
			else if (m.containsKey("interfacetest")) {
				this.interfaceTest(testfilepath,returnlist, (List<Map<String, Object>>)m.get(findContainsKey(m, "interfacetest")),tmpindex);
				continue;
			}
			else if (isMapContainsEqualsKey(m, "assert") && !unexcIndexstr.contains(findContainsKey(m, "assert"))) {
				excAssert(m);
				continue;
			}
			
			else if (isMapContainsEqualsKey(m, "sleep") && !unexcIndexstr.contains(findContainsKey(m, "sleep"))) {
				excSleep(m);
				continue;
			}
			
			else if (isMapContainsEqualsKey(m, "interface") && !isMapContainsEqualsKey(m,"interfacetest")) {
				this.interfaceTest(testfilepath, returnlist,(List<Map<String, Object>>)m.get(findContainsKey(m, "interface")),tmpindex);
				continue;
			}
			else if (isMapContainsEqualsKey(m, "mq") && !unexcIndexstr.contains(findContainsKey(m, "mq"))) {
				excMq(testfilepath, m);
				continue;
			}
			else if (isMapContainsEqualsKey(m, "sendmsg") && !unexcIndexstr.contains(findContainsKey(m, "sendmsg"))) {
				excSendmsg(testfilepath, m);
				continue;
			}
			else if (isMapContainsEqualsKey(m, "mysql") && !unexcIndexstr.contains(findContainsKey(m, "mysql"))) {
				excMysql(testfilepath, m);
				continue;
			}
			else if (isMapContainsEqualsKey(m, "mongo") && !unexcIndexstr.contains(findContainsKey(m, "mongo"))) {
				continue;
			}
			else if (isMapContainsEqualsKey(m, "kafka") && !unexcIndexstr.contains(findContainsKey(m, "kafka"))) {
				continue;
			}
		}
		
	}
	/**
	 * 返回对应check的index
	 * @param returnlist
	 * @param checkstr
	 * @return
	 */
	public static Integer getCheckIndex(List<Map<String, Object>> returnlist,String checkstr) {
		int index = -1;
		for (Map<String, Object> map: returnlist) {
			if (map.containsKey(checkstr.toLowerCase())) {
				index = returnlist.indexOf(map);
				break;
			}
		}
		return index;
	}
	/**
	 * 接口测试驱动
	 * 
	 * @param filepath
	 *            测试数据文件
	 * @param arr
	 *            测试数据
	 */
	@SuppressWarnings("unchecked")
	public void interfaceTest (String filepath,List<Map<String, Object>> returnlist, List<Map<String, Object>> interlist,int index) {
		for (Map<String, Object> returnmap : interlist) {
			String projecttype = returnmap.get("calltype").toString();
			String url = returnmap.get("url").toString();
//			String interfacedetail = returnmap.get("interfacedetail").toString();
			String method = returnmap.get("method").toString();
			Map<String, String> returns = (Map<String, String>) returnmap.get("returns");
			LinkedHashMap<String, String> datamap = (LinkedHashMap<String, String>) returnmap.get("datamap");
			String params = datamap.containsKey("params") ? datamap.get("params").toString() : "";
			String checks = datamap.containsKey("check") ? datamap.get("check").toString() : "";
			String expectedcode = datamap.containsKey("expectedcode") ? datamap.get("expectedcode").toString() : "";
			String expectedmsg = datamap.containsKey("expectedmsg") ? datamap.get("expectedmsg").toString() : "";
			String expectedresult = datamap.containsKey("expectedresult") ? datamap.get("expectedresult").toString() : "";
			String expectedreturn = datamap.containsKey("expectedreturn") ? datamap.get("expectedreturn").toString() : "";
			String globalparams = datamap.containsKey("globalparams") ? datamap.get("globalparams").toString() : "";
			String localparams = datamap.containsKey("localparams") ? datamap.get("localparams").toString() : "";
			if (!isStrEmpty(globalparams)) {
				if (!ObjectCompare.isJsonObject(globalparams)) {
					Assert.fail("参数传递globalparams必须输入json对象");
				}
			}
			if (!isStrEmpty(localparams)) {
				if (!ObjectCompare.isJsonObject(localparams)) {
					Assert.fail("参数传递localparams必须输入json对象");
				}
			}
			String resultnum = datamap.containsKey("resultnum") ? datamap.get("resultnum").toString() : "";
			try {
//				interfacedetail = replaceParam(interfacedetail,method);
				checks = replaceParam(checks,method);
				projecttype = replaceParam(projecttype,method);
				url = replaceParam(url,method);
				params = replaceParam(params,method);
				expectedcode = replaceParam(expectedcode,method);
				expectedmsg = replaceParam(expectedmsg,method);
				expectedresult = replaceParam(expectedresult,method);
				expectedreturn = replaceParam(expectedreturn,method);
				globalparams = replaceParam(globalparams,method);
				localparams = replaceParam(localparams,method);
				resultnum = replaceParam(resultnum,method);
			} catch (Exception e2) {
				// TODO Auto-generated catch block
				Assert.fail(e2.toString());
			}
			Map<String,Integer> afterExc = new LinkedHashMap<>();
			if (!isStrEmpty(checks)) {
				String checkarr[] = checks.split(";");
				for (String checkstr : checkarr) {
					int checkindex = getCheckIndex(returnlist, checkstr);
					if (-1 == checkindex) {
						Assert.fail("找不到对应check:"+checkstr);
					}
					else if(checkindex < index){
						if (checkstr.startsWith("assert")) {
							excAssert(returnlist.get(checkindex));
						}
						else if (checkstr.startsWith("sleep")) {
							excSleep(returnlist.get(checkindex));
						}
						else if (checkstr.startsWith("mq")) {
							excMq(filepath,returnlist.get(checkindex));
						}
						else if (checkstr.startsWith("sendmsg")) {
							excSendmsg(filepath,returnlist.get(checkindex));
						}
						else if (checkstr.startsWith("mysql")) {
							excMysql(filepath,returnlist.get(checkindex));
						}
						else if (checkstr.startsWith("mongo")) {
						}
						else if (checkstr.startsWith("kafka")) {
						}
					}
					else if (checkindex > index) {
						afterExc.put(checkstr, checkindex);
					}
				}
			}
			if (projecttype.equalsIgnoreCase("rpc")) {
				String[] urls = returnmap.get("url").toString().split(":");
				String service = method.split("\\.")[0];
				String testmethod = method.split("\\.")[1];
				// JSONObject iReturn = JSON.parseObject(RPCUtils.callRpcInterface(urls[0],
				// urls[1], service, testmethod, arr[5].toString()));
				JSONObject iReturn = new JSONObject();
				System.out.println(iReturn);
				if (!isStrEmpty(globalparams)) {
					globalparams = replaceParamAfter(globalparams, iReturn, returns);
					JSONObject jo = JSON.parseObject(globalparams);
					for (String k : jo.keySet()) {
						if (k.startsWith("data.") || k.startsWith("code.") || k.startsWith("message.") || set.contains(k) || k.equalsIgnoreCase("method") || k.equalsIgnoreCase("jsonresult")) {
							Assert.fail("全局变量不能使用已有系统参数(如method,jsonresult,code,message,data,code.*,message.*,data.*)");
						}
						else {
							put(parammap, k, jo.getString(k));
						}
					}
				}	
				if (!isStrEmpty(localparams)) {
					localparams = replaceParamAfter(localparams, iReturn, returns);
					JSONObject jo = JSON.parseObject(localparams);
					for (String k : jo.keySet()) {
						if (k.startsWith("data.") || k.startsWith("code.") || k.startsWith("message.") || set.contains(k) || k.equalsIgnoreCase("method") || k.equalsIgnoreCase("jsonresult")) {
							Assert.fail("局部变量不能使用已有系统参数(如method,jsonresult,code,message,data,code.*,message.*,data.*)");
						}
						else {
							put(this.localparamsmap, k, jo.getString(k));
						}
					}
				}
				if (!isStrEmpty(expectedreturn)) {
					if (expectedreturn.endsWith(".txt") || expectedreturn.endsWith(".json")
							|| expectedreturn.endsWith(".xml") || expectedreturn.endsWith(".properties")) {
						String expectreturnstr = null;
						try {
							expectreturnstr = org.apache.commons.io.FileUtils
									.readFileToString(getRelativePathFile(filepath, expectedreturn), "UTF-8");
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							Assert.fail(e.toString());
						}
						expectreturnstr = JSON.parse(expectreturnstr).toString();
						Assert.assertTrue(iReturn.toJSONString().contains(expectreturnstr));
					} else {
						Assert.assertTrue(iReturn.toString().contains(expectedreturn));
					}
				} 
				InterfaceCheck(returns, iReturn, expectedcode, expectedmsg, expectedresult, resultnum);				
			} else if (projecttype.contains("http")) {
				// String []url = arr[2].toString().split(";");
				// for (int i = 0; i < url.length; i++){
				// try{
				Map<String, String> headers = null;
				String body = null;
				try {
					headers = datamap.containsKey("headers") && !datamap.get("headers").toString().isEmpty()
							? JSON.parseObject(invokeAllMethod(replaceParam(datamap.get("headers").toString(),method)), new TypeReference<Map<String, String>>() {
							})
							: new HashMap<String, String>();
					body = datamap.containsKey("body") && !datamap.get("body").toString().isEmpty()
							? invokeAllMethod(replaceParam(datamap.get("body").toString(),method))
							: "";
				} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException
						| InstantiationException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					Assert.fail(e1.toString());
				} catch (ParamNotExistException e) {
					// TODO Auto-generated catch block
					Assert.fail(e.toString());
				}

				JSONObject iReturn = callInterface(url, projecttype.replaceFirst("http\\.", ""), params, headers, body);
				System.out.println(iReturn);
				if (!isStrEmpty(globalparams)) {
					globalparams = replaceParamAfter(globalparams, iReturn, returns);
					JSONObject jo = JSON.parseObject(globalparams);
					for (String k : jo.keySet()) {
						if (k.startsWith("data.") || k.startsWith("code.") || k.startsWith("message.") || set.contains(k) || k.equalsIgnoreCase("method") || k.equalsIgnoreCase("jsonresult")) {
							Assert.fail("自定义参数名不能使用已有系统参数(如method,jsonresult,code,message,data,code.*,message.*,data.*)");
						}
						else {						
							put(parammap, k, jo.getString(k));
						}
					}
				}	
				if (!isStrEmpty(localparams)) {
					localparams = replaceParamAfter(localparams, iReturn, returns);
					JSONObject jo = JSON.parseObject(localparams);
					for (String k : jo.keySet()) {
						if (k.startsWith("data.") || k.startsWith("code.") || k.startsWith("message.") || set.contains(k) || k.equalsIgnoreCase("method") || k.equalsIgnoreCase("jsonresult")) {
							Assert.fail("局部变量不能使用已有系统参数(如method,jsonresult,code,message,data,code.*,message.*,data.*)");
						}
						else {
							put(localparamsmap, k, jo.getString(k));
						}
					}
				}
				if (!isStrEmpty(expectedreturn)) {
					if (expectedreturn.endsWith(".txt") || expectedreturn.endsWith(".json")
							|| expectedreturn.endsWith(".xml") || expectedreturn.endsWith(".properties")) {
						String expectreturnstr = null;
						try {
							expectreturnstr = org.apache.commons.io.FileUtils
									.readFileToString(getRelativePathFile(filepath, expectedreturn), "UTF-8");
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							Assert.fail(e.toString());
						}
						expectreturnstr = JSON.parse(expectreturnstr).toString();
						Assert.assertEquals(iReturn.toJSONString(), expectreturnstr);
					} else {
						Assert.assertEquals(iReturn.toString(), expectedreturn);
					}
				} else {
					InterfaceCheck(returns, iReturn, expectedcode, expectedmsg, expectedresult, resultnum);
				}
			}
			
			for (String indexstr : afterExc.keySet()) {
				if (indexstr.startsWith("assert")) {
					excAssert(returnlist.get(afterExc.get(indexstr)));
				}
				else if (indexstr.startsWith("sleep")) {
					excSleep(returnlist.get(afterExc.get(indexstr)));
				}
				else if (indexstr.startsWith("mq")) {
					excMq(filepath,returnlist.get(afterExc.get(indexstr)));
				}
				else if (indexstr.startsWith("sendmsg")) {
					excSendmsg(filepath,returnlist.get(afterExc.get(indexstr)));
				}
				else if (indexstr.startsWith("mysql")) {
					excMysql(filepath,returnlist.get(afterExc.get(indexstr)));
				}
				else if (indexstr.startsWith("mongo")) {
				}
				else if (indexstr.startsWith("kafka")) {
				}
			}
		}		
	}
	/**
	 * 接口测试驱动
	 * 
	 * @param filepath
	 *            测试数据文件
	 * @param arr
	 *            测试数据
	 */
	@SuppressWarnings("unchecked")
	public void interfaceTestOld (String filepath, Object... arr) {
		localparamsmap = new HashMap<>();
		Map<String, Object> returnmap = (Map<String, Object>) arr[0];
		String projecttype = returnmap.get("calltype").toString();
		String url = returnmap.get("url").toString();
//		String interfacedetail = returnmap.get("interfacedetail").toString();
		String method = returnmap.get("method").toString();
		Map<String, String> returns = (Map<String, String>) returnmap.get("returns");
		LinkedHashMap<String, String> datamap = (LinkedHashMap<String, String>) returnmap.get("datamap");
		String params = datamap.containsKey("params") ? datamap.get("params").toString() : "";
		String checks = datamap.containsKey("check") ? datamap.get("check").toString() : "";
		String expectedcode = datamap.containsKey("expectedcode") ? datamap.get("expectedcode").toString() : "";
		String expectedmsg = datamap.containsKey("expectedmsg") ? datamap.get("expectedmsg").toString() : "";
		String expectedresult = datamap.containsKey("expectedresult") ? datamap.get("expectedresult").toString() : "";
		String expectedreturn = datamap.containsKey("expectedreturn") ? datamap.get("expectedreturn").toString() : "";
		String globalparams = datamap.containsKey("globalparams") ? datamap.get("globalparams").toString() : "";
		String localparams = datamap.containsKey("localparams") ? datamap.get("localparams").toString() : "";
		if (!isStrEmpty(globalparams)) {
			if (!ObjectCompare.isJsonObject(globalparams)) {
				Assert.fail("参数传递globalparams必须输入json对象");
			}
		}
		if (!isStrEmpty(localparams)) {
			if (!ObjectCompare.isJsonObject(localparams)) {
				Assert.fail("参数传递localparams必须输入json对象");
			}
		}
		String resultnum = datamap.containsKey("resultnum") ? datamap.get("resultnum").toString() : "";
		try {
//			interfacedetail = replaceParam(interfacedetail,method);
			checks = replaceParam(checks,method);
			projecttype = replaceParam(projecttype,method);
			url = replaceParam(url,method);
			params = replaceParam(params,method);
			expectedcode = replaceParam(expectedcode,method);
			expectedmsg = replaceParam(expectedmsg,method);
			expectedresult = replaceParam(expectedresult,method);
			expectedreturn = replaceParam(expectedreturn,method);
			globalparams = replaceParam(globalparams,method);
			resultnum = replaceParam(resultnum,method);
		} catch (Exception e2) {
			// TODO Auto-generated catch block
			Assert.fail(e2.toString());
		}
//		if (!isStrEmpty(checks)) {
//			String checkarr[] = checks.split(";");
//			for (String checkstr : checkarr) {
//				int index = getCheckIndex(returnlist, checkstr);
//				if (-1 == index) {
//					Assert.fail("找不到对应check:"+checkstr);
//				}
//				else {
//					returnlist.get(index).get(checkstr);
//				}
//			}
//		}
		if (projecttype.equalsIgnoreCase("rpc")) {
			String[] urls = returnmap.get("url").toString().split(":");
			String service = method.split("\\.")[0];
			String testmethod = method.split("\\.")[1];
			// JSONObject iReturn = JSON.parseObject(RPCUtils.callRpcInterface(urls[0],
			// urls[1], service, testmethod, arr[5].toString()));
			JSONObject iReturn = new JSONObject();
			System.out.println(iReturn);
			if (arr.length >= 12) {
				if (arr[10] instanceof HashMap) {
					for (Object key : ((HashMap<?, ?>) arr[10]).keySet()) {
						if (key.toString().equalsIgnoreCase("globalparams")) {
							globalparams = ((HashMap<?, ?>) arr[10]).get(key).toString();
							break;
						} else if (key.toString().equalsIgnoreCase("expectReturn")) {
							expectedreturn = ((HashMap<?, ?>) arr[10]).get(key).toString();
							break;
						}
					}
				}
				if (arr[11] instanceof HashMap) {
					for (Object key : ((HashMap<?, ?>) arr[11]).keySet()) {
						if (key.toString().equalsIgnoreCase("globalparams")) {
							globalparams = ((HashMap<?, ?>) arr[11]).get(key).toString();
							break;
						}
					}
				}
			}

			if (!isStrEmpty(globalparams)) {
				actualrm.put(globalparams,
						getJsonResult(getJsonReturn(returns.get("data").toString(), iReturn).toString()));
			}
			if (null != expectedreturn && !expectedreturn.isEmpty()) {
				if (expectedreturn.endsWith(".txt") || expectedreturn.endsWith(".json")
						|| expectedreturn.endsWith(".xml") || expectedreturn.endsWith(".properties")) {
					String expectreturn = null;
					try {
						expectreturn = org.apache.commons.io.FileUtils
								.readFileToString(getRelativePathFile(filepath, expectedreturn), "UTF-8");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					expectreturn = JSON.parse(expectreturn).toString();
					Assert.assertEquals(iReturn.toJSONString(), expectreturn);
				} else {
					Assert.assertEquals(iReturn.toString(), expectedreturn);
				}
			} else {
				InterfaceCheck(returns, iReturn, arr[6].toString(), arr[7].toString(), arr[8].toString(),
						arr[9].toString());
			}
		} else if (projecttype.contains("http")) {
			// String []url = arr[2].toString().split(";");
			// for (int i = 0; i < url.length; i++){
			// try{
			Map<String, String> headers = null;
			String body = null;
			try {
				headers = datamap.containsKey("headers") && !datamap.get("headers").toString().isEmpty()
						? JSON.parseObject(invokeAllMethod(replaceParam(datamap.get("headers").toString(),method)), new TypeReference<Map<String, String>>() {
						})
						: null;
				body = datamap.containsKey("body") && !datamap.get("body").toString().isEmpty()
						? invokeAllMethod(replaceParam(datamap.get("body").toString(),method))
						: null;
			} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException
					| InstantiationException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				Assert.fail(e1.toString());
			} catch (ParamNotExistException e) {
				// TODO Auto-generated catch block
				Assert.fail(e.toString());
			}

			JSONObject iReturn = callInterface(url, projecttype.replaceFirst("http\\.", ""), params, headers, body);
			System.out.println(iReturn);
			if (!isStrEmpty(globalparams)) {
				globalparams = replaceParamAfter(globalparams, iReturn, returns);
				JSONObject jo = JSON.parseObject(globalparams);
				for (String k : jo.keySet()) {
					if (k.startsWith("data.") || k.startsWith("code.") || k.startsWith("message.") || set.contains(k) || k.equalsIgnoreCase("method") || k.equalsIgnoreCase("jsonresult")) {
						Assert.fail("自定义参数名不能使用已有系统参数(如method,jsonresult,code,message,data,code.*,message.*,data.*)");
					}
					else {
						put(parammap, k, jo.getString(k));
					}
				}
			}	
			if (!isStrEmpty(localparams)) {
				localparams = replaceParamAfter(localparams, iReturn, returns);
				JSONObject jo = JSON.parseObject(localparams);
				for (String k : jo.keySet()) {
					if (k.startsWith("data.") || k.startsWith("code.") || k.startsWith("message.") || set.contains(k) || k.equalsIgnoreCase("method") || k.equalsIgnoreCase("jsonresult")) {
						Assert.fail("局部变量不能使用已有系统参数(如method,jsonresult,code,message,data,code.*,message.*,data.*)");
					}
					else {
						put(localparamsmap, k, jo.getString(k));
					}
				}
			}
			if (!isStrEmpty(expectedreturn)) {
				if (expectedreturn.endsWith(".txt") || expectedreturn.endsWith(".json")
						|| expectedreturn.endsWith(".xml") || expectedreturn.endsWith(".properties")) {
					String expectreturnstr = null;
					try {
						expectreturnstr = org.apache.commons.io.FileUtils
								.readFileToString(getRelativePathFile(filepath, expectedreturn), "UTF-8");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Assert.fail(e.toString());
					}
					expectreturnstr = JSON.parse(expectreturnstr).toString();
					Assert.assertEquals(iReturn.toJSONString(), expectreturnstr);
				} else {
					Assert.assertEquals(iReturn.toString(), expectedreturn);
				}
			} else {
				InterfaceCheck(returns, iReturn, expectedcode, expectedmsg, expectedresult, resultnum);
			}
		}
	}

	/**
	 * 获得当前类及其父类的所有方法,排除基类Object
	 * @param cls
	 * @return
	 */
	public static Method[] getAllMethodsList(final Class<?> cls) {
        Validate.isTrue(cls != null, "The class must not be null");
        final List<Method> allFields = new ArrayList<Method>();
        Class<?> currentClass = cls;
        while (currentClass != null) {
        	if (!currentClass.equals(Object.class)) {
        		final Method[] declaredFields = currentClass.getDeclaredMethods();
                for (final Method field : declaredFields) {
                    allFields.add(field);
                }
                currentClass = currentClass.getSuperclass();
        	}
        	else {
        		break;
        	}
        }
        return allFields.toArray(new Method[allFields.size()]);
    }
	/** 
     * 利用递归找一个类的指定方法，如果找不到，去父亲里面找直到最上层Object对象为止。 
     *  
     * @param clazz 
     *            目标类 
     * @param methodName 
     *            方法名 
     * @param classes 
     *            方法参数类型数组 
     * @return 方法对象 
     * @throws Exception 
     */  
    public static Method getMethod(Class clazz, String methodName,  
            final Class[] classes) throws Exception {  
        Method method = null;  
        try {  
            method = clazz.getDeclaredMethod(methodName, classes);  
        } catch (NoSuchMethodException e) {  
            try {  
                method = clazz.getMethod(methodName, classes);  
            } catch (NoSuchMethodException ex) {  
                if (clazz.getSuperclass() == null) {  
                    return method;  
                } else {  
                    method = getMethod(clazz.getSuperclass(), methodName,  
                            classes);  
                }  
            }  
        }  
        return method;  
    }  
    
    
}
